package com.example.tmtimer;

import android.media.AudioManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView mRemaining;
	CountDownTimer mTimer;
	// 20mins=1200000miliseconds
	final private int K_TM_DURATION_IN_MILISECONDS = 20000;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mRemaining = (TextView) findViewById(R.id.tvTimeLeft);
		prepareStart();
		
		mTimer.start();
	}

	private void prepareStart() {
		mRemaining.setKeepScreenOn(true);

		mTimer = new CountDownTimer(K_TM_DURATION_IN_MILISECONDS, 1000) {

			public void onTick(long millisUntilFinished) {
				mRemaining
						.setText(String.valueOf((millisUntilFinished / 1000)));
			}

			public void onFinish() {
				prepareFinish();
			}
		};
		setRingingMode(AudioManager.RINGER_MODE_SILENT);
	}

	private void prepareFinish() {
		mRemaining.setKeepScreenOn(false);
		setRingingMode(AudioManager.RINGER_MODE_NORMAL);
	}

	private void setRingingMode(int mode) {
		AudioManager audioManager = (AudioManager) this
				.getSystemService(Context.AUDIO_SERVICE);
		int maxVolume = audioManager
				.getStreamMaxVolume(AudioManager.STREAM_RING);

		audioManager.setRingerMode(mode);
		audioManager.setStreamVolume(AudioManager.STREAM_RING, maxVolume,
				AudioManager.FLAG_SHOW_UI + AudioManager.FLAG_PLAY_SOUND);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
